package org.example.test;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.example.mapper.EmpMapper;
import org.example.pojo.Emp;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;

/**
 * ClassName: EmpMapperTest
 * Package: org.example.test
 * Description:
 *
 * @Author wanghao
 * @Create 2024-07-01 16:02
 * @Version 1.0
 */
public class EmpMapperTest2 {

    private SqlSessionFactory sqlSessionFactory;

    @Before
    public void setup() throws IOException {
        InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    }

    // 验证二级缓存
    @Test
    public void testSecondLevelCacheExists() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        EmpMapper mapper = sqlSession.getMapper(EmpMapper.class);
        Emp emp = mapper.getEmpById(1);
        System.out.println("emp" + emp);

        // 在执行第二次查询之前关闭当前SqlSession
        sqlSession.close();

        // SqlSession关闭后，一级缓存中的内容会被存入二级缓存


        // 再次打开一个新的SqlSession
        sqlSession = sqlSessionFactory.openSession();
        mapper = sqlSession.getMapper(EmpMapper.class);
        emp = mapper.getEmpById(1);
        System.out.println("emp" + emp);
        sqlSession.close();
    }

    @Test
    public void testSecondLevelCacheExists2() {
        // 1. 开启两个SqlSession
        SqlSession sqlSession1 = sqlSessionFactory.openSession();
        SqlSession sqlSession2 = sqlSessionFactory.openSession();

        // 2. 获取Mapper对象
        EmpMapper mapper1 = sqlSession1.getMapper(EmpMapper.class);
        EmpMapper mapper2 = sqlSession2.getMapper(EmpMapper.class);

        // 3. 执行查询操作
        Emp emp1 = mapper1.getEmpById(1);
        sqlSession1.close();
        Emp emp2 = mapper2.getEmpById(1);

        // 4. 关闭SqlSession
//        sqlSession1.close();
        sqlSession2.close();

        // 5. 验证二级缓存是否存在
        System.out.println("emp1 = " + emp1);
        System.out.println("emp2 = " + emp2);
        System.out.println(emp2.equals(emp1));
    }
}
